package com.niodata.dp.expression.function.array;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

public class ArrayMaxFunction extends AbstractFunction {

  @Override
  public String getName() {
    return "array.max";
  }

  /**
   * find max value from list or array.
   *
   * @param env env
   * @param array array
   * @return max value
   */
  public AviatorObject call(Map<String, Object> env, AviatorObject array) {
    Object v = array.getValue(env);
    Comparable[] varray = null;
    if (List.class.isAssignableFrom(v.getClass())) {
      List<Comparable> list = (List) v;
      varray = list.toArray(new Comparable[list.size()]);
    } else if (v.getClass().isArray()) {
      int len = Array.getLength(v);
      varray = new Comparable[len];
      for (int i = 0; i < len; i++) {
        varray[i] = (Comparable) Array.get(v, i);
      }
    }
    if (varray.length == 0) {
      return FunctionUtils.wrapReturn(null);
    }
    Arrays.sort(varray, new Comparator<Comparable>() {
      @Override
      public int compare(Comparable o1, Comparable o2) {
        return o1.compareTo(o2);
      }
    });
    Comparable value = varray[varray.length - 1];
    return FunctionUtils.wrapReturn(value);
  }
}
